//
//  BookListTableViewController.m
//  XMLY
//
//  Created by 曾杰 on 15/11/10.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "BookListTableViewController.h"
#import "PKRequestManager.h"
#import "SoundBookModel.h"
#import "SoundBookCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "AlertView.h"
#import "MusicDetailViewController.h"
#import "CheckNetConnect.h"
#import "NetConnectView.h"
@interface BookListTableViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataArr;//数据数组
@property (nonatomic, strong)NetConnectView *connectView;
@property (nonatomic, strong)UITableView *bookList;
@property (nonatomic, assign)NSInteger pageId;
@end

@implementation BookListTableViewController

-(NSMutableArray *)dataArr
{
    if (_dataArr == nil) {
        self.dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}

//配置数据
- (void)configureData
{
    NSString * pageId =[NSString stringWithFormat:@"pageId=%ld",(long)self.pageId];
    NSRange range = [self.urlStr rangeOfString:@"pageId=1"];
    NSString * newUrl = [self.urlStr stringByReplacingCharactersInRange:range withString:pageId];

    [PKRequestManager requestWithType:GET urlString:newUrl parDic:nil finish:^(NSData *data) {
       
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
        
                NSArray *arr = dic[@"list"];
                for (NSDictionary *listDic in arr) {
                    SoundBookModel *model = [[SoundBookModel alloc]init];
                    [model setValuesForKeysWithDictionary:listDic];
                    [self.dataArr addObject:model];
                }
                [self.bookList reloadData];
                [self.bookList.header endRefreshing];
                [self.bookList.footer endRefreshing];
            
         

    } error:^(NSError *error) {
        
    }];
                           
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageId =1;
    self.bookList = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-100) style:(UITableViewStylePlain)];
    __weak typeof(self) weakSelf = self;
//    [self configureData];
    self.bookList.delegate = self;
    self.bookList.dataSource = self;
    [self.bookList registerClass:[SoundBookCell class] forCellReuseIdentifier:@"soundBookCell"];
    self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-100);
    [weakSelf checkNetConnectState];
    self.bookList.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.dataArr removeAllObjects];
//        [self configureData];
        self.pageId = 1;
        [weakSelf checkNetConnectState];
    }];
    self.bookList.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [self configureData];
        self.pageId ++;
        [weakSelf checkNetConnectState];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
//    return 0;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SoundBookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"soundBookCell" forIndexPath:indexPath];
    SoundBookModel *model = self.dataArr[indexPath.row];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.albumCoverUrl290]];
    cell.titleLabel.text = model.title;
    cell.introLabel.text = model.intro;
    float playsCount = model.playsCounts / 10000.0;
    cell.playCountLabel.text = [[NSString stringWithFormat:@"%.1f",playsCount] stringByAppendingString:@"万"];
    cell.tracksCounts.text = [[NSString stringWithFormat:@"%ld",(long)model.tracksCounts] stringByAppendingString:@"集"];
    
    return cell;
}
#pragma mark - UITableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDetailViewController *playListVC = [[MusicDetailViewController alloc]init];
    SoundBookModel *model = self.dataArr[indexPath.row];
    playListVC.albumId = [NSString stringWithFormat:@"%ld",(long)model.albumId];
    [self presentViewController:playListVC animated:YES completion:nil];
}

- (void)checkNetConnectState{
    
    BOOL netState = [[CheckNetConnect shareConnect] netConnectState];
    NSLog(@"+++%d", netState);
    if (netState == YES) {
        NSLog(@"开始刷新数据");
        [self.view addSubview:self.bookList];
        _connectView.frame = CGRectMake(0, - SCREEN_HEIGHT - 20, SCREEN_WIDTH, SCREEN_HEIGHT - 50) ;
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        [self configureData];
        
    }else{
        
        _connectView = [[NetConnectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:_connectView];
    }
    
}

// 重新请求数据
- (void)retryRequest{
    NSLog(@"重新刷新数据");
    [self checkNetConnectState];
}

@end
